package com.yonyou.iuap.base.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;

import com.yonyou.iuap.base.sl.DesUtils;

public class BaseToolsUtils {
	private static Properties pro;
	/**
	 * 根据request的输入流获取参数信息
	 * @param request
	 * @return
	 */
	public static  String getParamsByRequest(HttpServletRequest request){
		//获取post参数 
		StringBuffer sb = new StringBuffer() ; 
		InputStream is;
		try {
			is = request.getInputStream();
			InputStreamReader isr = new InputStreamReader(is);   
			BufferedReader br = new BufferedReader(isr); 
			String s = "" ; 
			while((s=br.readLine())!=null){ 
				sb.append(s) ; 
			} 
			String str =sb.toString(); 
			//防止用get传递参数 
			if(str.equals("")){ 
				if(request.getQueryString() != null) { 
					str = request.getRequestURL()+"?"+request.getQueryString(); 
				} else { 
					str = request.getRequestURL().toString(); 
				} 
			}
			return str;
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
			return null;
		} 
	}
	/**
	 * 根据属性文件名称以及key获取value
	 * @param fileName
	 * @return
	 */
	public static String getPropertiesValue(String fileName,String key){
		if(pro==null){
			InputStream is = null;
			pro = new Properties();
			try{
				is = BaseToolsUtils.class.getResourceAsStream(fileName);
				pro.load(is);
				if(key.startsWith("encrypt")){
					return DesUtils.decode(pro.getProperty(key));
				}else{
					return pro.getProperty(key);
				}
			}catch(Exception e){
				e.printStackTrace();
				return null;
			}finally{
				if(is!=null){
					try {
						is.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}else{
			if(key.startsWith("encrypt")){
				return DesUtils.decode(pro.getProperty(key));
			}else{
				return pro.getProperty(key);
			}
		}
	}
	
	/**
	 * 默认读application.properties文件
	 * @param key
	 * @return
	 */
	public static String getPropertiesValue(String key){
		return getPropertiesValue("/application.properties", key);
	}
}
